package com.zhouyong.netty.handler;

import com.zhouyong.message.RpcResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 99Savage
 * @date 2023/3/17 10:16
 */
@Component
@Slf4j
public class CustomizeClientHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {
    public static final Map<Integer, Promise<Object>> map = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext context, RpcResponseMessage message) throws Exception {
        log.info("[channelRead0]客户端接收服务端的消息为: {}", message);

        // 发送处理结果给到服务端
        Promise<Object> promise = map.get(message.getSequenceId());
        if (!(HttpStatus.OK.value() == message.getCode())) {
            promise.setFailure(new Exception("执行错误"));
        } else {
            promise.setSuccess(message.getData());
        }
    }
}
